package com.chap13;

import java.util.concurrent.RecursiveTask;

/**
 * <p>
 * <code>LongSum</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-04-12 10:40
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class LongSum extends RecursiveTask<Long> {
    static final int THRESHOLD = 1000;

    int low;
    int high;
    int[] array;

    public LongSum(int[] array,int low, int high) {
        this.low = low;
        this.high = high;
        this.array = array;
    }


    @Override
    protected Long compute() {
        if (high-low<THRESHOLD){
            long sum = 0;
            for (int i = low; i < high; i++) {
                sum+=array[i];
            }
            return  sum;
        }else {
            int mid = low+(high-low)/2;
            LongSum left = new LongSum(array,low,mid);
            LongSum right = new LongSum(array,mid,high);

            left.fork();
            right.fork();

            Long rightResult = right.join();
            Long leftResult = left.join();
            return rightResult+leftResult;
        }
    }
}
